/*
 *
 * Copyright (C) 2007-2009 Kai 'Oswald' Seidler, http://oswaldism.de
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 675 Mass
 * Ave, Cambridge, MA 02139, USA. 
 * 
 */

var timeout = 60*60; // set update frequency to 60 minutes 
var now=0;
var timeoutevent=0;

// many parts of this Widged were based on Apple's Widget tutorial at
// http://developer.apple.com/documentation/AppleApplications/Conceptual/Dashboard_ProgTopics/

function showBack()
{
    var front = document.getElementById("front");
    var back = document.getElementById("back");

    if (window.widget)
        widget.prepareForTransition("ToBack");

    front.style.display="none";
    back.style.display="block";

    if (window.widget)
        setTimeout ('widget.performTransition();', 0);  

}

function hideBack()
{
    var front = document.getElementById("front");
    var back = document.getElementById("back");

    if (window.widget)
    {
	var form=document.getElementById("ff");

	if(form.username.value!="" && form.password.value!="")
	{
		widget.setPreferenceForKey(form.username.value, "username");

		now=0;
		showDialog("Saving to keychain...");
		var command=widget.system("./AppSalesWidget.php setcredentials", onshow);
		command.write(form.username.value+"\n");
		command.write(form.password.value+"\n");
		command.close();

		form.password.value="";
	}
    }


    if (window.widget)
        widget.prepareForTransition("ToFront");

    back.style.display="none";
    front.style.display="block";

    if (window.widget)
    {
        setTimeout ('widget.performTransition();', 0);
    }
}

function showDialog(message)
{
	dialog_content.innerHTML=message;
	dialog.style.display="block";
	front_content.style.display="none";
}

function hideDialog()
{
	front_content.style.display="block";
	dialog.style.display="none";
}

function endHandler()
{
}

function fetchData()
{
	var command=widget.system("./AppSalesWidget.php getdata", displayData);
	command.write(widget.preferenceForKey("username")+"\n");
	command.close();
}

function displayData(data)
{
	
	if (data.outputString.search(/#/i) == -1){
		showDialog("<span class=\"smaller\">"+data.outputString+"</span>");
		return;
	}
	
	output=data.outputString.split("#");

	// do we get real data
	if(output.length == 7) 
	{
		document.getElementById("updated").innerHTML=output[0];
		document.getElementById("earnings").innerHTML="$"+output[1];
		document.getElementById("paid").innerHTML=output[2];
		document.getElementById("free").innerHTML=output[3];
		document.getElementById("paid_u").innerHTML=output[4];
		document.getElementById("free_u").innerHTML=output[5];		
		document.getElementById("extrapolated").innerHTML="$"+output[6];
		
		now = Math.round(new Date().getTime()/1000);

		hideDialog();
	}
	else
	{
		showDialog("<span class=\"small\">Did not get AppStore data</span><br><span class=\"smaller\">"+data.outputString+"</span>");
	}

	if(timeoutevent!=0)
	{
		clearTimeout(timeoutevent);
	}
	timeoutevent=setTimeout('fetchData();',timeout*1000);
}

function onshow()
{
	if(widget.preferenceForKey("username")!=undefined && widget.preferenceForKey("username")!="")
	{
		if(now && Math.round(new Date().getTime()/1000)-now<timeout)
		{
			// still not the time to fetch new AppStore data
		}
		else
		{
        		showDialog("Loading...");

			setTimeout('fetchData()',100);
		}
	}
	else
	{
  		showDialog("Please set username and<br>password on the back side.");
	}
}

function onhide()
{
}

function setup()
{
	if (window.widget) 
	{
		widget.onshow = onshow;
		widget.onhide = onhide;

		var form=document.getElementById("ff");
		form.username.value=widget.preferenceForKey("username");
	}
	var done_button = new AppleGlassButton(document.getElementById("done"), "Done", hideBack);
	i_button = new AppleInfoButton(document.getElementById("i"), document.getElementById("front"), "white", "white", showBack);
	document.getElementById("version").innerHTML = getPlistProperty("Info", "CFBundleVersion");

	var dialog = document.getElementById("dialog");
	var dialog_content = document.getElementById("dialog_content");
	var front_content = document.getElementById("front_content");

}

function getPlistProperty(filename, property)
{
	
	// check the parameters
	if( (filename == null) || (filename == "") ){ return null; }
	if( (property == null) || (property == "") ){ return null; }
	
	// retrieve the value with the defaults command
	return widget.system('/bin/sh -c "defaults read `pwd`/'+ filename + ' ' + property + '"',null).outputString;
}